//采购合同号、含税货款金额、总金额、申请金额、供应商合同号、款项类型、付款基准日、付款申请子项号
function getPaymentSubOptions(flag) {
    var initOptions = {
        idField: 'cid',
        fitColumns: false,
        checkOnSelect: false,
        singleSelect: false,
        fit: false,
        columns: [[{
            width: 20,
            checkbox: true
        },{
                hidden:'true',
                title: '采购合同号id',
                field: 'f_contractId',
                width: 150
            },{
            title: '采购合同号',
            field: 'contractCode',
            width: 100
        }, {
            title: '含税货款金额',
            field: 'taxAmount',
            width: 100,
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'totalAmount',
            title: '总金额',
            width: 100,
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        }, {
            field: 'appBalance',
            title: '<label class="redSharp">*申请金额</label>',
            width: 100,
            editor: {
                type: 'numberbox',
                options: {
                    precision:2,
                    required: true,
                    validType: ['noEmptyNumber','biggerAppBalance["#appOld"]']
                }
            },
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        },  {
            field: 'paidAmount',
            title: '实付金额',
            width: 100,
            align:'right',
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                return formatNum(value);
            }
        },
            {
            field: 'privoderCcode',
            title: '供应商合同号',
            width:110
        }, {
            field: 'moneyType',
            title: '款项类型',
            width: 100,
            formatter: function (value, rowData, rowIndex) {//格式化该字段内的显示
                for (var i = 0; i < payMethodJson.length; i++) {
                    if (payMethodJson[i].id == value) {
                        return payMethodJson[i].orName;
                    }
                }
            },
            editor: {
                type: 'combobox',
                options: {
                    required: true,
                    data: payMethodJson,
                    valueField: 'id',
                    textField: 'orName',
                    editable: false
                }
            }
        }, {
            field: 'paymentDate',
            title: '付款基准日',
            width: 100,
            align:'right',
            editor: {
                type: 'datebox'
            }
        },{
                field: 'remark',
                title: '备注',
                width: 100,
                editor: {
                    type: 'text'
                }
            },{
            field: 'padAppSub',
            title: '付款申请子项号',
            width: 100
        }]],
        toolbar: [{
            id: "addSub",
            text: '新增子项',
            iconCls: 'icon-add',
            handler: function () {
                selectPaymentSubItermPage("edit");
            }
        }, '-', {
            id: "deleteSub",
            text: '删除子项',
            iconCls: 'icon-remove',
            handler: function () {
                delPaymentSubIterm();
            }
        }],
        onBeforeEdit:function(rowIndex, rowData){
            $('#appOld').text(rowData.totalAmount);
        },
        onClickCell: onClickCell,
        onAfterEdit: function (rowIndex, rowData, changes) {
            calculatePaymentToTop();
        }
    }
    //新增分支 主要是hidden 隐藏 所以默认edit
    if(!flag){
        initOptions.columns[0][6].hidden = 'true';
        initOptions.toolbar[0].handler = function(){
            selectPaymentSubItermPage();
        };
        initOptions.toolbar[1].handler = function(){
            delPaymentSubIterm();
        }
    }
    return initOptions;
}

function onClickCell(index, field) {
    if (endEditing($('#subItem'))) {
        if (checkLineStatus($('#subItem'), index)) {
            $('#subItem').datagrid('selectRow', index)
                .datagrid('editCell', {index: index, field: field});
            var ed = $('#subItem').datagrid('getEditor', {index: index, field: field});
            if (ed && ed.target) {
                $(ed.target).focus();
            }
            editIndex = index;
        }
    }
}

function checkLineStatus(node, index) {
    var rows = node.datagrid('getRows');
    if (rows && rows[index]) {
        if (!rows[index].statusSub) {
            return true;
        }
        if (rows[index].statusSub != "执行") {
            return false;
        } else {
            return true;
        }
    }
}

//刷新采购申请页面
function refreshPaymentPage(data) {
    //上部init
    loadData(data.object.paidApplication);
    $('#appAmount').numberbox('setValue',data.object.paidApplication.appAmount);
    $('#realAmount').numberbox('setValue',data.object.paidApplication.realAmount);
    $('#paidStarttime').datebox({
        required: true,
        editable: false
    });
    $('#paidStarttime').datebox("setValue", data.object.paidApplication.paidStarttime);
    //下部init
    if (data.object.paidApplication.id) {
        var options = getPaymentSubOptions("edit");
    } else {
        var options = getPaymentSubOptions();
    }

    options.data = data.object.paidApplicationSubList;
    $.each(options.data, function (index, value) {
        value.cid = UUID();
    })
    initDataGridNoPager($('#subItem'), options);
    setPaymentAddButtonsStatus(data.object.paidApplication.paidStatus);
}

//4、新增状态的采购申请单可以新增子项、删除子项、修改保存、手工提交、撤销申请。
//5、提交状态的采购申请单可以撤销提交、打印。
//6、审批不通过状态的采购申请单可以新增子项、删除子项、修改保存、手工提交、撤销申请。
//7、审批通过 财务拨付 撤销状态的采购申请单不能做任何操作
function setPaymentAddButtonsStatus(status) {
    var nodeArray = [$("#addSub"), $("#deleteSub"), $("#editPaFunction"),
        $("#handlePaSubmitFunction"), $("#cancelPaSubmitFunction"),
        $("#cancelPaFunction"),
        $("#printPaFunction")];
    if (status === "新增"||status === "审批不通过") {
        setLinkButtonStatus(nodeArray, [1, 1, 1, 1, 0, 1, 1]);
    } else if (status === "撤销" || status === "财务拨付"|| status === "审批通过") {
        setLinkButtonStatus(nodeArray, [0, 0, 0, 0, 0, 0, 1]);
    } else if (status === "提交") {
        setLinkButtonStatus(nodeArray, [0, 0, 0, 0, 1, 0, 0]);
    }
}

function preparePaymentSubmitPostData(flag) {
    endEditing($('#subItem'));
    var paymentData= {};
    var postData = $('#searchForm-small').serializeJson();
    //状态码
    postData.paidStatus = changeStatusVal($('#paidStatus').val(), paidStatus);
    if (flag == undefined) {
        //商户代码 商户名称
        var menberNoRow = $('#memberNo').combogrid('grid').datagrid('getSelected');
        postData.providerName = menberNoRow.memberName;
        postData.providerCode = menberNoRow.memberNo;
    } else {
        postData.id = $('#paymentApId').text();
    }
    postData.paidStarttime = $('#paidStarttime').datebox("getText");
    //子项表数据
    var subRows = $('#subItem').datagrid('getRows');

    //数据主体结构
    paymentData.paidApplication = postData;
    paymentData.paidApplicationSubList = subRows;
    return paymentData;
}

function preparePaymentSubmitRealPostData(flag) {
    var data = preparePaymentSubmitPostData(flag);
    $.each(data.paidApplicationSubList, function (index, value) {
        value.paidStatus = changeStatusVal(value.paidStatus, paidStatus);
        delete value.cid;
    });
    return data;
}


function getPaymentDetail(data) {
    parent.$.modalDialog.handler.dialog('close');
    var options = {"id": data.object.paidApplication.id};
    editPayApFunction(options);
}

//为$('#subItem') 增加子项
function selectPaymentSubItermPage(flag) {
    if(flag){
        var memberNoNode = $("#memberNo").val();
    }else{
        var memberNoNode = $("#memberNo").combogrid('grid').datagrid('getSelected');
    }
    if(memberNoNode){
        var options = {
            "width":880,"height":540,
            "href":getContextPath() + '/payment/paymentApAddSub.html?id=' + memberNoNode.memberNo,
            buttons: [{
                id: "addPaymentSubFunction",
                text: '确定',
                handler: function () {
                    //parent.$.modalDialog.openner_treeGrid = dataGridNode;
                }
            },{
                text: '返回',
                handler: function () {
                    parent.$.modalSubDialog.handler.dialog('close');
                }
            }]}
        addSubFun('采购合同列表', '/payment/paymentApAddSub.html?id=',$("#subItem"), options);
    }else{
        $.messager.alert('提示', '请选择供应商！', 'error');
    }
}

//删除子项
function delPaymentSubIterm() {
    var rows = $('#subItem').datagrid('getChecked');
    var cunzaiIds = [];
    var ids = [];
    if (rows.length > 0) {
        $.each(rows, function (index, value) {
            if (value.id) {
                cunzaiIds.push(value.id);
            }
            ids.push(value.cid);
        });
        if (cunzaiIds.length > 0) {
            $.messager.confirm('请确认', '您要删除当前所选项目？', function (r) {
                if (r) {
                    var postData = {
                        'paidApplicationId': $("#paymentApId").text(),
                        'paidApplicationSubIds': cunzaiIds
                    }
                    postAjax("/payment/deleteOnePaidApplicationSub.html", JSON.stringify(postData),
                        refreshPaymentPage);
                    calculateToTop();
                }
            });
        } else if (ids.length > 0) {
            $.messager.confirm('请确认', '您要删除当前所选项目？', function (r) {
                if (r) {
                    $.each(ids, function (index, value) {
                        $('#subItem').datagrid('deleteRow', $('#subItem').datagrid('getRowIndex', value));
                    });
                    calculateToTop();
                }
            });
        } else {
            $.messager.alert('提示', '请选择要删除的记录！', 'error');
        }
    }
}
